package com.moleq.dialog;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.moleq.base.MoleQBaseDialog;
import com.moleq.device.DeviceManager;
import com.moleq.enums.ItemType;
import com.moleq.enums.TransactionType;
import com.moleq.logic.MoleQConstants;
import com.moleq.logic.TransactionManager;
import com.moleq.mgpos.activities.R;
import com.moleq.mgpos.activities.SaleActivity;
import com.moleq.mgpos.widget.DisplayScreen;
import com.moleq.mgpos.widget.NumberPad;
import com.moleq.mgpos.widget.NumberPad.NumberPadListener;
import com.moleq.mgpos.widget.NumberPadButton;
import com.moleq.models.Departmant;
import com.moleq.models.FreeFuncRpt;
import com.moleq.models.GlobalInfo;
import com.moleq.models.SaleListItem;
import com.moleq.models.TareSetting;
import com.moleq.service.DepartmantService;
import com.moleq.service.ServiceManager;
import com.moleq.util.BigDecmialTool;
import com.moleq.util.MoleQUtil;

public class OpenDeptDialog extends MoleQBaseDialog {

	private Button mButtonBack;
	private TransactionManager mPaymentMgr;
	private Context mContext;
	private SaleActivity sa;
	private ListView mListView;
	private List<Departmant> DataSource = new  ArrayList<Departmant>();
	private List<TareSetting> mTareSetting = new ArrayList<TareSetting>();
	private DepartmantService service = null;
	private OpenDepartmantAdapter mAdapter;
	private NumberPad numberPanel;
	private TextView tv_qty;
	private int currentQty = 1;
//	private CheckBox cb_weight;
	private DeviceManager mDeviceManager; //contral device scanner or scale
	private Button.OnClickListener mOnClickListener = new Button.OnClickListener() {

		@Override
		public void onClick(View v) {

			switch (v.getId()) {
			case R.id.btn_dialog_open_dep_back:
				mDeviceManager.enableAllScanner();
				dismiss();
				break;
			}

		}
	};


	public OpenDeptDialog(Context context) {
		super(context,R.style.dialog,context);
		constructor(context);
		sa = (SaleActivity) context;
	}


	public OpenDeptDialog(Context context, int theme) {
		super(context, theme);
		constructor(context);
	}
	
	
	private void constructor(Context context) {
		mContext = context;
	}
	

	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// set UI layout
		this.setContentView(R.layout.dialog_open_dept);
		this.setCancelable(false);
	
		mButtonBack = (Button) findViewById(R.id.btn_dialog_open_dep_back);
		mButtonBack.setOnClickListener(mOnClickListener);
		
		mListView = (ListView) findViewById(R.id.lv_dialog_open_dep_list);
		mAdapter = new OpenDepartmantAdapter(mContext);
		mListView.setAdapter(mAdapter);
		mListView.setDivider(null);
		
		numberPanel = (NumberPad) this.findViewById(R.id.NumberPadOpenDep);
		numberPanel.setStyle(NumberPad.SALE_STYLE);
		numberPanel.setNumberPadListener(mNumberPadListener );
		
		tv_qty = (TextView) findViewById(R.id.tv_dialog_open_dep_qty);
//		cb_weight = (CheckBox) findViewById(R.id.cb_weight);
		
	}
	
	public void show(){
		super.show();
		
		mPaymentMgr =  TransactionManager.getInstance();
		mDeviceManager = DeviceManager.getInstance();
		mDeviceManager.disableAllScanner();
		service = ServiceManager.getInstance().mDepartmantService;
		DataSource = service.FindAll();
		mAdapter.notifyDataSetChanged();
		currentQty = 1;
		tv_qty.setText("1");
		numberPanel.setQty(1);
		numberPanel.requestFocusFromTouch();
		numberPanel.setBuffer("");
//		cb_weight.setChecked(false);
	}
	
	private NumberPadListener mNumberPadListener = new NumberPadListener(){

		@Override
		public void onClick(NumberPadButton button) {
			switch (button) {
			case ENTER:
				
				break;
			case MULTIPLY:
				currentQty = numberPanel.getQty();
				tv_qty.setText(String.valueOf(numberPanel.getQty()));
				break;
			default:
				//
				break;
			}
			
		}
		
	};
	
	class OpenDepartmantAdapter extends BaseAdapter{
		private Context maContext;
		public final class ViewHolder{
			public Button btn_dep_name;
		}
		
		public OpenDepartmantAdapter(Context context){
			maContext = context;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return DataSource.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return DataSource.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			ViewHolder holder = null;
			if(convertView == null){
				holder = new ViewHolder();
				
				convertView = LayoutInflater.from(maContext).inflate(R.layout.dep_list_item, null);
				holder.btn_dep_name = (Button) convertView.findViewById(R.id.btn_dep_list_item);
				
				convertView.setTag(holder);
			}else{
				holder = (ViewHolder) convertView.getTag();
			}
			boolean scale = DataSource.get(position).getScale_weight();
			if (scale) {
				holder.btn_dep_name.setBackgroundResource(R.drawable.btn_background_green);
			}else {
				holder.btn_dep_name.setBackgroundResource(R.drawable.btn_background);
			}
			
			String content = DataSource.get(position).getDep_no() + "  " + DataSource.get(position).getDep_name();
			
			holder.btn_dep_name.setText(content);
			holder.btn_dep_name.setTag(DataSource.get(position));
			
			holder.btn_dep_name.setOnClickListener(adapterOnClickListener);
			
			return convertView;
		}
	}
	
	private Button.OnClickListener adapterOnClickListener = new Button.OnClickListener(){

		@Override
		public void onClick(View view) {
			// TODO Auto-generated method stub
//			onCloseWithReturn(viewId, parm);
		
			String price = numberPanel.getBuffer();
			if (price.equals(".")) {
				return;
			}
			if(price.trim().length() > 0){
				
				String tmp =numberPanel.getBuffer();
				
				double paid = Double.valueOf(tmp);
				if (!price.contains(".")) {
					paid /= 100; 
				}
				if (paid <= 0 || paid > 99999) {
					return;
				}
				
				Departmant departmant = (Departmant) view.getTag();
//				numberPanel.setBuffer(departmant.getDep_name());
				SaleListItem newItem = mPaymentMgr.mSaleListItems.createItem();
				newItem.setUnitPrice(paid);
				newItem.setPrice(paid * currentQty);
				newItem.setName(departmant.getDep_name());
				newItem.setQty(currentQty);
				//===code by feng 0621=====
				newItem.setUpc("D"+String.valueOf(departmant.getDep_no()+"|"+newItem.getId()));
				newItem.setTax1(departmant.getTax1());
				newItem.setTax2(departmant.getTax2());
				newItem.setTax3(departmant.getTax3());
				newItem.setTax4(departmant.getTax4());
				newItem.setTax5(departmant.getTax5());
				newItem.setTax6(departmant.getTax6());
				newItem.setNodiscount(departmant.getNo_discnt());
				newItem.setFoodstamp(departmant.getFood_stamp());
				newItem.setItemType(ItemType.OPEN_DEPARTMENT);
				newItem.setRefund(sa.mRefundMode);
//				newItem.setId(mPaymentMgr.mSaleListItems.generateID());
				newItem.setAge(ServiceManager.getInstance().mAgeSettingService.FindAge(departmant.getAge()));
				newItem.setWic(departmant.isWic());
				newItem.setCvv(departmant.isCvv());
				//===================
				newItem.setDep_group(departmant.getGroup_no());
				newItem.setMdepartment(departmant.getDep_no());
				newItem.setIsWeight(departmant.getScale_weight());
				
				if (currentQty > 1) {
					if (newItem.getIsWeight()) {
						
					}else{
						
						newItem.setEachDescription(newItem.getQty() + " @ 1 / "+MoleQUtil.fixPriceForScreen(newItem.getUnitPrice()));
					}
//					newItem.setEachDescription(MoleQUtil.fixPriceForScreen(newItem.getUnitPrice())+" EACH");
					
				}
				
				onReturnValue(MoleQConstants.FUNCTION_OPEN_DEPARTMENT, newItem);
				//======= wei ==========
//				double openWeight = 0;
//				String currentWeightDesc = "";
////				if (cb_weight.isChecked()) {
//				if (departmant.getScale_weight()) {
//					if (mDeviceManager.scaleIsReady) {
//						openWeight = mDeviceManager.scale.getWeight();
////						openWeight = 1.98;
//						openWeight = BigDecmialTool.round(openWeight, getUnit());
//						if (openWeight == 0) {
//							mDeviceManager.disableAllScanner();
//							MessageBox.show(mContext,sa.getResources().getString(R.string.msg_no_weight));
//							return;
//						}
//						newItem.setPrice(paid * openWeight);
//						newItem.setWeight(openWeight);
//						newItem.setIsWeight(true);
//						
//						
//						
//						
//						if (mPaymentMgr.manualTare > 0) {
//							double tare = mPaymentMgr.manualTare * GlobalInfo.getInstance().tareRate;
//							newItem.setPrice(paid * (openWeight - tare));
//							newItem.setWeight(openWeight - tare);
//							newItem.setmTareDesc(" Tare " + MoleQUtil.fixWeight(tare, getUnit()));
//							TareSetting tsetting = new TareSetting();
//							tsetting.setTa_no(0);
//							tsetting.setQty(mPaymentMgr.manualTare);	
//							mTareSetting.add(tsetting);
//							newItem.setTareCount(1);
//							newItem.setmTareSetting(mTareSetting);
//							GlobalInfo.getInstance().useFuntionsList.add(GlobalInfo.getInstance().CurrentFreeFuncID);
//							mPaymentMgr.SaveFreeFuncRpt(GlobalInfo.getInstance().CurrentFreeFuncID, 1, 0);
//						}
//						currentWeightDesc = MoleQUtil.fixWeight(newItem.getWeight(), getUnit()) +  GlobalInfo.getInstance().weightUnit;
//						currentWeightDesc += " @ " + GlobalInfo.getInstance().CurrencySign + MoleQUtil.fixNumber(paid) + "/" + GlobalInfo.getInstance().weightUnit;
//						newItem.setWeightDesc(currentWeightDesc);
//						newItem.setDepDescription("  " + currentWeightDesc);
//					}
//					
//				}
//
////				}
////				sa.setManualTare(0);
//				mPaymentMgr.manualTare = 0;
//				newItem.setDisplayContent(newItem.getName() + " " + newItem.getWeightDesc() + newItem.getmTareDesc());
//				////////////////////////
//				
//				numberPanel.setBuffer("");
////				mPaymentMgr.addItem(newItem);
//				
////				mPaymentMgr.mSaleListItems.addItem(newItem);
//				mPaymentMgr.mSaleListItems.addItemToList(newItem);
//				if (sa.mRefundMode) {
//					mPaymentMgr.SaveFreeFuncRpt(FreeFuncRpt.FF_REFUND, 1, newItem.getPrice());
//				}
//				sa.mRefundMode = false; //cancel refund
//				DisplayScreen.getInstance().showItemToDisplayScreen(newItem);
//				mPaymentMgr.announceChanges();
				mDeviceManager.enableAllScanner();
//				OpenScanner();
				dismiss();
//				onCloseWithReturn(R.id.btn_dialog_open_dep_back, "");
			}
		}
		
	};

	
//	public int getUnit() {
//		int checkunit = 2;
//		String unit = ServiceManager.getInstance().mPosSettingService.Find().getPs_weight_unit();
//		if (unit.equals("oz")) {
//			checkunit = 1;
//		} else if (unit.equals("lb")) {
//			checkunit = 2;
//		} else if (unit.equals("kg")) {
//			checkunit = 3;
//		}
//		return checkunit;
//	}
}
